package jblip.gui.components;

import java.awt.Dimension;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeNode;

import jblip.gui.IconLoader;
import jblip.gui.JBlip;
import jblip.gui.components.tree.ChannelTree;
import jblip.gui.components.tree.UpdatesChannelNode;
import jblip.gui.data.channels.DashboardChannel;
import jblip.gui.data.channels.DataChannel;
import jblip.gui.data.channels.UpdatesDataChannel;

public class ChannelFrame extends JFrame implements TreeSelectionListener {
  private static final long serialVersionUID = 1L;

  private static final String FRAME_TITLE = "JBlip-dev";

  static final ImageIcon ICON_FRAME;

  static {
    ICON_FRAME = IconLoader.loadIcon("jblip-icon.png");
  }

  private ImageIcon ICON_CONF;

  private ImageIcon ICON_EXIT;

  private ImageIcon ICON_TRACKING;

  private ImageIcon ICON_RELOGIN;

  private ActionPanel view_pane;

  public void viewChannel(final UpdatesDataChannel channel) {
	  view_pane.viewChannel(channel);
  }
  
  public ChannelFrame() {
    super(FRAME_TITLE);
    this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    this.setLocationRelativeTo(null);
    initListeners();
    initIcons();
    initMenu();
    initUI();
    this.pack();
    this.setVisible(true);
  }

  private void initListeners() {
    this.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        if (JOptionPane.showConfirmDialog(
            ChannelFrame.this, "Czy na pewno zamknąć JBlip?", "Zamknąć się?",
            JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) {
          // if this fails, we might need to call checkExit on a SecurityManager
          System.exit(0);
        }
      }
    });
  }

  private void initIcons() {
    MediaTracker tracker = new MediaTracker(this);
    ICON_CONF = IconLoader.loadIcon("icon-configure.png");
    ICON_EXIT = IconLoader.loadIcon("icon-exit.png");
    ICON_TRACKING = IconLoader.loadIcon("icon-tracking.png");
    ICON_RELOGIN = IconLoader.loadIcon("icon-relogin.png");

    tracker.addImage(ICON_CONF.getImage(), 1);
    tracker.addImage(ICON_EXIT.getImage(), 2);
    tracker.addImage(ICON_TRACKING.getImage(), 3);
    tracker.addImage(ICON_RELOGIN.getImage(), 4);
    tracker.addImage(ICON_FRAME.getImage(), 5);

    try {
      tracker.waitForAll();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    this.setIconImage(ICON_FRAME.getImage());
  }

  private void initMenu() {
    final JMenuBar menubar = new JMenuBar();

    final JMenu blip_menu = new JMenu("Blip");
    final JMenuItem mi_relog = new JMenuItem("Zmień użytkownika", ICON_RELOGIN);
    final JMenuItem mi_track = new JMenuItem("Obserwowani", ICON_TRACKING);
    final JMenuItem mi_conf = new JMenuItem("Konfiguruj", ICON_CONF);

    mi_conf.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent e) {
        new ConfigFrame();
      }
    });

    // TODO: add action listener to remaining menu items

    final JMenuItem mi_exit = new JMenuItem("Wyjdź", ICON_EXIT);
    mi_exit.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        processWindowEvent(new WindowEvent(ChannelFrame.this,
            WindowEvent.WINDOW_CLOSING));
      }
    });

    blip_menu.add(mi_track);
    blip_menu.add(mi_conf);
    blip_menu.addSeparator();
    blip_menu.add(mi_relog);
    blip_menu.add(mi_exit);

    menubar.add(blip_menu);
    this.setJMenuBar(menubar);
  }

  private void initUI() {
    final DashboardChannel dashboard = DataChannel.getDashboardChannel();
    final ChannelTree tree = new ChannelTree();
    tree.addTreeSelectionListener(this);
    final JScrollPane left_pane = new JScrollPane(tree);
    left_pane
        .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    view_pane = new ActionPanel();
    view_pane.viewChannel(dashboard);

    final int viewpane_width =
        JBlip.instance().getConfiguration().getViewWidth();
    view_pane.setPreferredSize(new Dimension(viewpane_width, view_pane
        .getHeight()));

    final JSplitPane split =
        new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, left_pane, view_pane);
    split.setDividerLocation(0.5);
    this.add(split);
  }

  @Override
  public synchronized void valueChanged(final TreeSelectionEvent ev) {
    final TreeNode sel =
        (TreeNode) ev.getNewLeadSelectionPath().getLastPathComponent();
    if (sel instanceof UpdatesChannelNode) {
      UpdatesChannelNode node = (UpdatesChannelNode) sel;
      System.err.println("Selected channel node: "
          + node.getChannel().getName());
      final UpdatesDataChannel channel = node.getChannel();
      view_pane.viewChannel(channel);
    }
  }
}
